package com.boarsoft.boar.batch.demo.flow.demo;

import com.boarsoft.boar.batch.demo.entity.EmpSalary;
import com.boarsoft.boar.batch.service.BatchReportService;
import com.boarsoft.common.util.InetUtil;
import com.boarsoft.flow.core.bean.ForkHandler;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 模拟拆分页
 *
 * @author wangtao
 */
public class DemoForkHD implements ForkHandler {

    private static final int PAGE_SIZE = 10;

    @Autowired
    private BatchReportService batchReportService;

    @Override
    public Map<String, Object> fork(String key, Object data, Throwable throwable) {
        System.out.println(" do DemoForkHD...");

        List<EmpSalary> empList = (ArrayList<EmpSalary>) data;
        int totalCount = empList.size();
        int totalPage = (totalCount % PAGE_SIZE == 0) ? (totalCount / PAGE_SIZE) : (totalCount / PAGE_SIZE + 1);
        //搞个10下
        Map<String, Object> map = new HashMap<>();
        //按分页安排数据
        for (int i = 1; i <= totalPage; i++) {
            map.put("" + i, listPage((long) i, (long) PAGE_SIZE, empList));
        }

        /**
         * 批量进度上报
         * 此节点为多任务执行前节点，上报一次后续总共有多少个分页需要执行以及预期该阶段执行需要的占比。
         */
//        batchReportService.report("123456", "DemoForkHD", InetUtil.getIp(), totalPage, totalCount,80);
        return map;
    }

    private static List listPage(Long pageIndex, Long pageSize, List list) {
        if (pageIndex.equals(0L)) {
            pageIndex = 1L;
        }
        int totalRecord = list.size();
        Long totalPage = totalRecord % pageSize;
        if (totalPage > 0) {
            totalPage = totalRecord / pageSize + 1;
        } else {
            totalPage = totalRecord / pageSize;
        }
        Long currentPage = totalPage < pageIndex ? totalPage : pageIndex;
        int fromIndex = (int) (pageSize * (currentPage - 1));
        int toIndex = pageSize * currentPage > totalRecord ? totalRecord : (int) (pageSize * currentPage);
        return list.subList(fromIndex, toIndex);
    }

}
